﻿<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <meta charset="utf-8"/>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>

<p><input type="file" id="upfile">
</p>
<p><input type="button" id="upJS" value="用原生JS上传">
</p>
<p><input type="button" id="upJQuery" value="用jQuery上传">
</p>

</body>

<script>
    // jQuery版
    $('#upJQuery').on('click', function () {
        var fd = new FormData();
        fd.append("upload", 1);
        fd.append("upfile", $("#upfile").get(0).files[0]);
        $.ajax({
            url: "/api/Upload",
            type: "POST",
            processData: false,
            contentType: false,
            data: fd,
            success: function (d) {
                console.log(d);
                $("body").append("<img src='{0}'/>".format(d));
            }
        });
    });



    String.prototype.format = function (args) {
        var result = this;
        if (arguments.length > 0) {
            if (arguments.length == 1 && typeof (args) == "object") {
                for (var key in args) {
                    if (args[key] != undefined) {
                        var reg = new RegExp("({" + key + "})", "g");
                        result = result.replace(reg, args[key]);
                    }
                }
            }
            else {
                for (var i = 0; i < arguments.length; i++) {
                    if (arguments[i] != undefined) {
                        //var reg = new RegExp("({[" + i + "]})", "g");//这个在索引大于9时会有问题，谢谢何以笙箫的指出

                        var reg = new RegExp("({)" + i + "(})", "g");
                        result = result.replace(reg, arguments[i]);
                    }
                }
            }
        }
        return result;
    }
</script>
</html>
